﻿#region File Description
//Physics Engine
#endregion

#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
#endregion

namespace Squog_1._1.Managers
{
    /// <summary>
    /// This is the PhysicsManager
    /// </summary>
    public class PhysicsManager : GameComponent
    {
        #region Members

        private static List<PhysicsObject> Elements = new List<PhysicsObject>();
        public static Vector2 Gravity { get; set; }
        private static Terrain terrain;

        #endregion

        #region Initilization

        /// <summary>
        /// Constructor
        /// </summary>
        public PhysicsManager(Game game)
            : base(game)
        {
            Gravity = new Vector2(0,9.8f);
        }

        /// <summary>
        /// Inilitization
        /// </summary>
        public override void Initialize()
        { }

        #endregion

        #region Update

        /// <summary>
        /// Updates game logic
        /// </summary>
        public override void Update(GameTime gameTime)
        {
            for (int i = 0; i < Elements.Count; i++)
            {
                if (!Elements[i].IsStatic)
                    Elements[i].PhysicsUpdate(gameTime);
            }

            base.Update(gameTime);
        }
        
        #endregion

        #region Methods
        public static void Add(PhysicsObject element)
        {
            Elements.Add(element);
        }

        public static void Clear()
        {
            Elements.Clear();
        }
        #endregion

        public static void SetTerrain(Terrain terrain)
        {
            PhysicsManager.terrain = terrain;
        }

        public static List<LineSegment> GroundCheck(Rectangle collisionRect)
        {
            return terrain.IsColliding(collisionRect);
        }


        //Added In by Justin
        public static List<PhysicsObject> CollisionCheck(Vector2 Position, float Radius)
        {
            List<PhysicsObject> L = new List<PhysicsObject>();
            foreach (PhysicsObject o in Elements)
                if(CircleRectCollision(Position, Radius, o.collisionRect))
                    L.Add(o);
            return L;
        }

        public static bool CircleRectCollision(Vector2 Position, float Radius, Rectangle CollisionRect)
        {
            Vector2 CenterRect = new Vector2(CollisionRect.Center.X,CollisionRect.Center.Y);
            return (Position - CenterRect).Length() <= ((CollisionRect.Height / 2) + Radius);
        }
    }
}
